const mysql = require('mysql2/promise');
const axios = require('axios');
const fs = require('fs');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'chatime'
});

const API_BASE = 'http://10.133.25.98:3000/api';
const senderId = 'user1';
const receiverId = 'user2';
const message = '自动测试好友申请';

async function main() {
  try {
    // 1. 清理历史数据
    await pool.execute("DELETE FROM friend_requests WHERE (sender_id=? AND receiver_id=?) OR (sender_id=? AND receiver_id=?)", [senderId, receiverId, receiverId, senderId]);
    await pool.execute("DELETE FROM friends WHERE (user_id=? AND friend_id=?) OR (user_id=? AND friend_id=?)", [senderId, receiverId, receiverId, senderId]);
    console.log('✅ 已清理历史数据');

    // 2. 发送好友申请（模拟前端请求）
    const reqBody = { userId: senderId, targetUserId: receiverId, message };
    console.log('🌐 发送好友申请请求:', reqBody);
    let apiResp;
    try {
      apiResp = await axios.post(`${API_BASE}/friend/request`, reqBody);
      console.log('🌐 接口返回:', apiResp.data);
    } catch (e) {
      console.error('❌ 接口请求失败:', e.response?.data || e.message);
      return;
    }

    // 3. 检查数据库写入
    const [requests] = await pool.execute(
      'SELECT * FROM friend_requests WHERE sender_id=? AND receiver_id=? ORDER BY create_time DESC',
      [senderId, receiverId]
    );
    if (requests.length === 0) {
      console.log('❌ 数据库未写入任何申请');
    } else {
      requests.forEach(r => {
        console.log(`  id=${r.id}, sender=${r.sender_id}, receiver=${r.receiver_id}, status=${r.status}, create_time=${r.create_time}`);
      });
      const pending = requests.filter(r => r.status === 'pending');
      if (pending.length > 0) {
        console.log(`✅ 有${pending.length}条pending状态的好友申请`);
      } else {
        console.log('⚠️ 没有pending状态的好友申请');
      }
    }

    // 4. 检查API拉取
    const apiUrl = `${API_BASE}/friend/requests/${receiverId}`;
    const res = await axios.get(apiUrl);
    if (res.data && res.data.success) {
      const data = res.data.data;
      if (data.length === 0) {
        console.log('❌ API拉取为空，页面不会显示任何申请');
      } else {
        data.forEach(r => {
          console.log(`  [API] id=${r.id}, sender=${r.sender_id}, receiver=${r.receiver_id}, status=${r.status}, create_time=${r.create_time}`);
        });
        console.log(`✅ API拉取${data.length}条申请`);
      }
    } else {
      console.log('❌ API拉取失败', res.data);
    }
  } catch (error) {
    console.error('❌ 检查失败:', error);
  } finally {
    await pool.end();
  }
}

main(); 